package com.xxrl.shop.config.service;


import com.xxrl.shop.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author mis
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    private final UserService userService;

    public UserDetailsServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {

        logger.info("login by {}.",username);
        if (username == null || "".equals(username)) {
            throw new UsernameNotFoundException("用户不能为空");
        }
        com.xxrl.shop.domain.User user = userService.getUserByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        logger.info("login by {}.",username);

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //获取该用户所拥有的权限
        List<String> sysPermissions = userService.getPermissionByRole(user.getRole());
        // 声明用户授权
        sysPermissions.forEach(sysPermission -> grantedAuthorities.add(new SimpleGrantedAuthority(sysPermission)));
        return new User(user.getName(),user.getPassword(),grantedAuthorities);
    }
}
